<template>
	<view class="sse-demo">
		<view class="status-bar">
			<text :class="['status-dot', connected ? 'connected' : 'disconnected']"></text>
			<text>{{ connected ? '已连接' : '未连接' }}</text>
		</view>
		
		<view class="message-list">
			<view v-for="(msg, index) in messages" :key="index" class="message-item">
				<text class="message-type">{{ msg.type }}</text>
				<text class="message-content">{{ JSON.stringify(msg.data) }}</text>
				<text class="message-time">{{ formatTime(msg.timestamp) }}</text>
			</view>
		</view>
		
		<view class="control-panel">
			<button @click="startSSE" :disabled="connected">开始连接</button>
			<button @click="stopSSE" :disabled="!connected">断开连接</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			connected: false,
			messages: [],
			eventSource: null,
			responseData: null
		}
	},
	methods: {
		startSSE() {
			// 新方式：使用EventSource对象（H5+环境）
			if (window.EventSource) {
				this.eventSource = new EventSource('https://fc-mp-b492c6ff-a40d-4b8e-a8de-018848168fa0.next.bspapp.com/sse');
				
				this.eventSource.onopen = () => {
					this.connected = true;
					console.log('SSE连接已打开');
				};
				
				this.eventSource.onmessage = (event) => {
					this.handleSSEData(event.data);
				};
				
				this.eventSource.onerror = (error) => {
					console.error('SSE错误:', error);
					this.stopSSE();
				};
			} else {
				// 备用方式：使用uni.request
				uni.request({
					url: 'https://fc-mp-b492c6ff-a40d-4b8e-a8de-018848168fa0.next.bspapp.com/sse',
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200) {
							this.connected = true;
							this.responseData = res;
							this.handleSSEData(res.data);
						}
					},
					fail: (err) => {
						console.error('SSE连接失败:', err);
						this.connected = false;
					}
				});
			}
		},
		
		stopSSE() {
			if (this.eventSource) {
				this.eventSource.close();
				this.eventSource = null;
			}
			if (this.responseData) {
				// 尝试关闭请求（在某些环境下可能不支持）
				if (this.responseData.abort) {
					this.responseData.abort();
				}
				this.responseData = null;
			}
			this.connected = false;
		},
		
		handleSSEData(data) {
			try {
				const parsedData = JSON.parse(data);
				this.messages.unshift({
					type: parsedData.type || 'unknown',
					data: parsedData,
					timestamp: Date.now()
				});
				
				// 限制消息列表长度
				if (this.messages.length > 50) {
					this.messages.pop();
				}
			} catch (e) {
				console.error('解析SSE数据失败:', e, data);
				// 尝试处理可能是纯文本的数据
				if (typeof data === 'string') {
					this.messages.unshift({
						type: 'raw',
						data: { message: data },
						timestamp: Date.now()
					});
				}
			}
		},
		
		formatTime(timestamp) {
			const date = new Date(timestamp);
			return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
		}
	},
	
	beforeDestroy() {
		this.stopSSE();
	}
}
</script>

<style lang="scss">
.sse-demo {
	padding: 20px;
	
	.status-bar {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
		
		.status-dot {
			width: 10px;
			height: 10px;
			border-radius: 50%;
			margin-right: 10px;
			
			&.connected {
				background-color: #4CAF50;
			}
			
			&.disconnected {
				background-color: #F44336;
			}
		}
	}
	
	.message-list {
		height: 70vh;
		overflow-y: auto;
		border: 1px solid #eee;
		border-radius: 5px;
		padding: 10px;
		
		.message-item {
			padding: 10px;
			border-bottom: 1px solid #eee;
			
			.message-type {
				font-weight: bold;
				margin-right: 10px;
			}
			
			.message-time {
				font-size: 12px;
				color: #999;
				margin-left: 10px;
			}
		}
	}
	
	.control-panel {
		margin-top: 20px;
		display: flex;
		justify-content: space-around;
		
		button {
			width: 40%;
		}
	}
}
</style> 